/*
 * @Author: yangzonglong
 * @Date: 2021-07-20 10:51:25
 * @version: v1.0.0
 * @Descripttion: mobile radio
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-30 16:07:10
 * @Auditor:
 */
import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { List, Checkbox } from 'antd-mobile';
import RequiredMark from './RequiredMark';

const MobileRadio = ({ checkboxProps, formItemProps, initialValue, disabled }, ref) => {
  const [checkeds, setCheckeds] = useState([]);

  useEffect(() => {
    if (Array.isArray(initialValue)) setCheckeds(initialValue);
  }, [initialValue]);

  useImperativeHandle(ref, () => ({
    getData: () => checkeds,
  }));

  const onChange = (e) => {
    if (checkeds.some((item) => item === e)) setCheckeds(checkeds.filter((item) => item !== e));
    else setCheckeds(checkeds.concat(e));
  };

  return (
    <List
      renderHeader={() => (
        <span>
          {formItemProps?.required && <RequiredMark />}
          {formItemProps?.label}
        </span>
      )}
    >
      {checkboxProps?.dataSource?.map((item) => (
        <Checkbox.CheckboxItem disabled={disabled} onChange={() => onChange(item.value)} checked={checkeds.includes(item.value)} key={item.value}>
          {item.label}
        </Checkbox.CheckboxItem>
      ))}
    </List>
  );
};

export default forwardRef(MobileRadio);
